<?php
class Auth {

	/**
	 * 
	 * @var Callback
	 */
	protected $hashFun;
	/**
	 * 
	 * @var PDIO
	 */
	protected $pdio;
	private $err = array();
	
	
	public function __construct($p, $hF = false) {
		
		if ($hF === false) {
			$hF = function($pwd){return hash('whirlpool', $pwd);};
		}
		
		if (!is_callable($hF)) {
			throw new TypeMismatchException('Auth constuctor. Second paramter must be a callable');
		}
		
		$this->hashFun = $hF;
		$this->pdio = $p;
		
	}
	
	public function getErr() {
		return $this->err;
	}
	
	public function login($uname, $pwd) {
		
		list($storedHpwd, $salt) = AuthDao::getHPwd($this->pdio, $uname);
		$hpwd = $this->hash($salt.$pwd);
		
		$logOk = ($storedHpwd == $hpwd);
		
		if ($logOk) {
			$token = base64_encode(mcrypt_create_iv(128));
			AuthDao::insertToken($this->pdio, $uname, $token);
			if (!$this->setCookies($uname, $token)) {
				throw new FWerrorException('errore cookie');
			}
		}
		
		return $logOk;
	}

	
	public function register($uname, $pwd) {
		
		$salt = base64_encode(mcrypt_create_iv(128));
		
		$hpwd = $this->hash($salt.$pwd);
		
		$res = AuthDao::register($this->pdio, $uname, $hpwd, $salt);
		
		if ($res === false) {
			$this->err = $this->pdio->errorInfo();
			return false;
		}
		
		return true;
	}
	
	private function setCookies($uname, $token) {
		
		if (setcookie(COOKUSER, $uname, (time()+2592000), '/','',0) &&
			setcookie(COOKTOKEN, $token, (time()+2592000), '/','',0)) {
				return true;
		}
			
		return false;	
		
	}
	
	
	public function logged() {
		
		if (!nvli($_COOKIE, COOKUSER, false) || !nvli($_COOKIE, COOKTOKEN, false)) {
			return false;
		}
		
		if ($_COOKIE[COOKTOKEN] != AuthDao::getToken($this->pdio, $_COOKIE[COOKUSER])) {
			return false;
		}
		
		return true;
		
	}
	
	public function hash($str) {
		
		$callable = $this->hashFun;
		return $callable($str);
		
	}
	
	public static function linklogout() {
		return "index.php?ctrl=Auth&act=logout";
	}
	
}


